package com.syj.collect.Present;

import android.util.Log;

import com.google.gson.Gson;
import com.syj.collect.base.BasePresent;

import com.syj.collect.entry.DetailBean;
import com.syj.collect.entry.KeyvalueBean;
import com.syj.collect.entry.MyCollectBean;
import com.syj.collect.entry.StationDetailBean;
import com.syj.collect.entry.UserInfoBean;
import com.syj.collect.entry.WaterColorBean;
import com.syj.collect.http.BaseObserver;
import com.syj.collect.http.BaseRequest;
import com.syj.collect.utils.SPUtil;
import com.syj.collect.view.ProjectDetailView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class ProjectDetailPresent extends BasePresent<ProjectDetailView> {

    public void getDetailData(String id) {

        BaseRequest.getInstance().getApiServise().getDetailData(id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public boolean onSuccess(String value) {
//                        Log.e("station", value);
                        Gson gson = new Gson();
                        DetailBean gbean = gson.fromJson(value, DetailBean.class);
                        if (gbean.getCode() == 0) {
                            view.initSuccess(gbean.getData());
                        } else {
                            view.initFail(gbean.getMsg());
                        }

                        return false;
                    }

                    @Override
                    public void onFailure(Throwable e) throws Exception {
                        view.initFail("网络异常");
                    }

                    @Override
                    public void onEnd() {

                    }
                });
    }


    List<String> sublist = new ArrayList<>();

    public void upLoadFiles(boolean isSave, String did, String stationCode, List<String> imgs, List<DetailBean.DataDTO.ImgMapDTO> imgold, List<KeyvalueBean> date, String fixMsg, String supplyMsg, String selectSpinner) {
        //upLoadFile(imgs.get(0));
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        sublist.clear();
        boolean is_subFile = false;
        for (int i = 0; i < imgs.size(); i++) {
            if (!imgs.get(i).contains("http")) {
                is_subFile = true;//是否需要提交文件
//                Log.e("subfiles", imgs.get(i));

                File file = new File(imgs.get(i));
                // create RequestBody instance from file
                MultipartBody.Part part = MultipartBody.Part.createFormData("files", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
                MultipartBody.Part part1 = MultipartBody.Part.createFormData("describes", file.getName()/*, RequestBody.create(MediaType.parse("text/plain"), file.getName())*/);
                builder.addPart(part);
                builder.addPart(part1);
            } else {
                for (int o = 0; o < imgold.size(); o++) {
                    if (imgs.get(i).contains(imgold.get(o).getUrl())) {
                        if(!sublist.contains(imgold.get(i).getId()))sublist.add(imgold.get(i).getId());
                    }
                }

//                Log.e("subfiles", imgs.get(i));
            }

        }

        if (!is_subFile) {
            saveDate(isSave, did, stationCode, sublist, date, fixMsg, supplyMsg, selectSpinner);

        } else {

            MultipartBody multipartBody = builder.build();
            BaseRequest.getInstance().getApiServise().saveImg(multipartBody).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseObserver<String>() {
                        @Override
                        public boolean onSuccess(String value) {
//                            Log.e("files", value);

                            try {
                                JSONObject jsonObject = new JSONObject(value);
//                                Log.e("结果 :", value);
                                String msg = jsonObject.getString("msg");
                                int code = jsonObject.getInt("code");
                                if (code == 0) {
                                    //view.initSuccess(msg);
                                    JSONObject data = jsonObject.getJSONObject("data");
                                    JSONArray old = data.getJSONArray("ids");
//                                    Log.e("ooooooo", old.get(0).toString());
                                    for (int m = 0; m < old.length(); m++) {
                                        sublist.add(old.get(m).toString());
                                    }
                                    saveDate(isSave, did, stationCode, null, date, fixMsg, supplyMsg, selectSpinner);
                                } else {
                                    view.initFail(msg);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            return false;
                        }

                        @Override
                        public void onFailure(Throwable e) throws Exception {
//                            Log.e("files", e.toString());
                            view.initFail(e.toString());
                        }

                        @Override
                        public void onEnd() {

                        }
                    });
        }
    }


    public void saveDate(boolean isSave, String did, String stationCode, List<String> string, List<KeyvalueBean> date, String fixMsg, String supplyMsg, String selectSpinner) {
        for (int s = 0; s < sublist.size(); s++) {
            Log.e("subfiless", sublist.get(s));
        }




        HashMap hashMap = new HashMap();
        Gson gson = new Gson();
        UserInfoBean.UserInfo gsb = gson.fromJson(SPUtil.getPrefString("userInfo", ""), UserInfoBean.UserInfo.class);
        hashMap.put("id", did);//修改时用
        hashMap.put("addMsg", "" + supplyMsg);//补充信息
        //hashMap.put("auditMsg", "无");//审核意见
        hashMap.put("anionic", "" + date.get(1).getValue());//阴离子表面活性
        //hashMap.put("auditStatus", ""+0);//0 2 3  未  通过  未通过
        hashMap.put("cod", "" + date.get(0).getValue());//化学量
        hashMap.put("fileIds", sublist);
        hashMap.put("nh3", date.get(4).getValue());//氨氮
        hashMap.put("pollutionStatus", "" + fixMsg);//污染状况
        hashMap.put("isSubmit", isSave ? "" + 0 : "" + 1);//1,0
        hashMap.put("stationCode", "" + stationCode);//站点编号
        hashMap.put("tn", "" + date.get(3).getValue());//总氮
        hashMap.put("tp", "" + date.get(2).getValue());//总磷
        //hashMap.put("reportDate", "");
        hashMap.put("createBy", "" + gsb.getUserId());//创建人id

        hashMap.put("remarks", "" + selectSpinner);//水体色
        Gson gson1 = new Gson();
        Log.e("param :", gson1.toJson(string));
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), gson1.toJson(hashMap));
        BaseRequest.getInstance().getApiServise().saveDate(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public boolean onSuccess(String value) {
                        try {
                            JSONObject jsonObject = new JSONObject(value);
//                            Log.e("Interceptor1结果 :", value);
                            String msg = jsonObject.getString("data");////{"msg":"success","code":0,"data":"新增成功！"} 还中文了
                            int code = jsonObject.getInt("code");
                            if (code == 0) {
                                view.initSuccess(msg);
                            } else {
                                view.initFail(msg);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        return false;
                    }

                    @Override
                    public void onFailure(Throwable e) throws Exception {
                        view.initFail("网络异常");
                    }

                    @Override
                    public void onEnd() {

                    }
                });
    }


}
